/**
 * Created by Administrator on 2016/6/7.
 */
$(function () {

  //图片加载完成后再执行
  window.onload = function () {
    //初始化窗口大小和位置
    console.log('窗口高度',$(window).height());
    var win_w = $(window).width();
    var win_h = $(window).height();
    $('.im-wrap').css({"margin-top":(win_h - 840)/2 + 'px'});
    //初始化表情框的样式
    $('#expression-btn').qqFace({
      assign:'expression-input', //给输入框赋值
      path:'/img/face/'    //表情图片存放的路径
    });

    //颜色拾取器
    $(".color-select-btn").colorpicker({
      target:'#ipt-content',
      success:function(o,color){
        $("#color").val(color);
        //$('#ipt-content').css({'color': color});
      },
      reset:function(o){
        $("#color").val('');
      }
    });

    //计算chatlist高度
    var chatList = $('.im-chat-list');
    var children = chatList.children();
    console.log('开始，总高度', getTotalHeight(children));
    chatList.scrollTop(getTotalHeight(children) - chatList.height());

    //初始化输入框的字体，大小，颜色
    $('#ipt-content').css({'font-family': $('.font-family-select').val(),'font-size': $('.font-size-select').val()+'px'});

  };

  //动态调整聊天窗口大小和位置
  $(window).resize(function () {
    var width = $(this).width();
    var height = $(this).height();
    console.log('窗口大小',width+"*"+height);
  });

  //字体设置栏
  $('#font-btn').createFontBar();
  $('#font-btn').on('click', function () {
    $('#facebox').hide();
  });
  $('#expression-btn').on('click', function (e) {
    $('.font-bar').hide();
  });

  //切换客服
  $('.im-title').on('click', function () {
    $(this).removeClass('normal').addClass('spe');
    $(this).siblings('.im-title').removeClass('spe').addClass('normal');
  });

  //右侧信息栏tab点击
  $('.im-shop-tab .tab-item').on('click', function () {
    $(this).children('.tab-content').removeClass('not-current').addClass('current');
    $(this).siblings().children('.tab-content').removeClass('current').addClass('not-current');
  });

  //上传图片
  var uploader = new plupload.Uploader({
    runtimes: 'html5,flash,silverlight,html4',
    browse_button : 'upload-btn', //触发文件选择对话框的按钮，为那个元素id
    url : '/upload', //服务器端的上传页面地址
    flash_swf_url : '/lib/plupload/js/Moxie.swf', //swf文件，当需要使用swf方式进行上传时需要配置该参数
    silverlight_xap_url : '/lib/plupload/js/Moxie.xap', //silverlight文件，当需要使用silverlight方式进行上传时需要配置该参数
    filters: {
      mime_types : [
        { title : 'Image files', extensions : 'jpg,gif,png' }
      ],
      max_file_size: '1mb'
    },
    init: {
      QueueChanged: function () {
        uploader.start();
      },
      FileUploaded: function (uploader,file,res) {
        var data = JSON.parse(res.response);
        console.log('返回的文本', data);
        $('#ipt-content').append(
          '<img src=' + data.result + ' data-ext=' + data.ext + '>'
        );
      }
    }
  });
  uploader.init();

  //监听输入框的内容变化
  $('#ipt-content').on('change', function () {
    console.log('文字长度',$(this).text().length);
    $('#still-count').html(350 - $(this).text().length);
  });



  //发送消息
  var sdk = new WSDK();
  sdk.Base.login({
    uid: 'test_user',
    credential: '123456',
    appkey: '23383870',
    timeout: 5000,
    success: function(data){
      // {code: 1000, resultText: 'SUCCESS'}
      console.log('login success', data);
    },
    error: function(error){
      // {code: 1002, resultText: 'TIMEOUT'}
      console.log('login fail', error);
    }
  });

  //Event.on('CHAT_START_RECEIVE_MSG', function(data){
  //  console.log('我与touid之间的所有消息', data);
  //});
  //
  //Event.on('MSG_RECEIVED', function(data){
  //  console.log('我与touid之间能收到成功的消息', data);
  //});
  //
  //Event.on('CHAT.MSG_RECEIVED', function(data){
  //  console.log('我与touid之间能收到成功的单聊消息', data);
  //});
  //
  //Event.on('KICK_OFF', function(data){
  //  console.log('啊，我被踢了', data);
  //});
  //sdk.Chat.startListenMsg({
  //  touid: 'tb0197962:test3'
  //});
  $('.im-send.send-btn').on('click', function () {
    //var groupid = $('select').val();
    //addMsg('我', $('textarea').val());
    //var data = {
    //  touid: 'tb0197962:test',
    //  msg: $('textarea').val(),
    //  success: function (data) {
    //    console.log('消息发送成功', data);
    //  },
    //  error: function (error) {
    //    console.log('消息发送失败', error);
    //  }
    //};
    //if (groupid) {
    //  data.groupid = parseInt(groupid);
    //}
    //console.log(data);
    //sdk.Chat.sendMsgToCustomService(data);
    //$('textarea').val('');
    var chatList = $('.im-chat-list');
    var $content = $('#ipt-content').contents();
    var $group = $('<div>');
    var msgText = '';
    console.log('$content', $content);

    $content.each(function(index, ele){
      var $ele = $(ele);
      console.log('$ele',$ele);
      if($ele.is('img')) {
        var url = $ele.attr('src');

        sdk.Chat.sendMsgToCustomService({
          touid: 'tb0197962:test3',
          msgType: 1,
          msg: url,
          success: function(data){
            console.log('图片消息发送成功', data);
            chatList.append(msgTemplate('Javen', sendMsgTime(), $ele));
            chatList.scrollToBottom();
          },
          error: function(error){
            console.log('图片消息发送失败', error);
          }
        });
      } else {
        msgText +=  $ele.text() + '\n';
        $group.append($ele.text() + '<br>');
        console.log('msg...', msgText);
      }
      if(index == $content.length - 1 && $group.text()) {
        sdk.Chat.sendMsgToCustomService({
          touid: 'tb0197962:test3',
          msgType: 0,
          msg: msgText,
          success: function(data){
            console.log('文字消息发送成功', data);
            $group.append('</div>');
            chatList.append(msgTemplate('Javen', sendMsgTime(), $group));
            console.log('$group', $group);
            chatList.scrollToBottom();
            //清空编辑区
            $('#ipt-content').html('');
          },
          error: function(error){
            console.log('文字消息发送失败', error);
          }
        });
      }
    });

  });



  //消息模板
  //user
  function msgTemplate(user,time,$content) {
    var temp = '<div class="im-item im-me">' +
      '<div class="im-message clearfix">' +
      '<div class="im-user-area">' +
      '<a class="im-user-pic" href="#">'+
      '<img alt src="/img/user/user1.png">'+
      '<img class="im-user-pic-cap" alt src="/img/cap.png">'+
      '</a></div>' +
      '<div class="im-message-detail">' +
      '<table class="im-message-table">' +
      '<tbody>' +
      '<tr><td class="lt"></td><td class="ct"></td><td class="rt"></td></tr>' +
      '<tr><td class="lm"></td>' +
      '<td class="cm">' +
      '<div class="message-title">' +
      '<p class="message-owner">' + user + '</p>' +
      '<span class="send-time">' + time + '</span></div>' +
      '<div class="message-content"></div></td>' +
      '<td class="rm"><span></span></td></tr>' +
      '<tr><td class="lb"></td><td class="cb"></td><td class="rb"></td></tr></tbody></table></div></div></div>';
    var $temp = $(temp);
    $temp.find('.message-content').append($content);
    return $temp;
  }

  //求im-chat-list的总高度
  function getTotalHeight(list) {
    var totalHeight = 0;
    for (var i=0; i<list.length; i++) {
      //消息泡上下margin各为7px
      totalHeight += list[i].scrollHeight + 14;
    }
    return totalHeight;
  }

  //chatlist滚动到底部
  $.fn.scrollToBottom = function () {
    var children = this.children();
    this.scrollTop(getTotalHeight(children) - this.height());
  };


  //生成消息发送时间
  function sendMsgTime() {
    var date = new Date();
    var hour = date.getHours();
    var min = date.getMinutes();
    var sec = date.getSeconds();
    var time = hour + ':' + min + ':' + sec;
    return time;
  }

});
